package com.xuanyuanxinyu.core.task;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class SimpleTaskExecutor extends TaskExecutor {

    private static volatile SimpleTaskExecutor sInstance;

    @NonNull
    private TaskExecutor mDelegate;

    @NonNull
    private final TaskExecutor mDefaultTaskExecutor;

    private SimpleTaskExecutor() {
        mDefaultTaskExecutor = new DefaultTaskExecutor();
        mDelegate = mDefaultTaskExecutor;
    }

    public static SimpleTaskExecutor getInstance() {
        if (null == sInstance) {
            synchronized (SimpleTaskExecutor.class) {
                if (null == sInstance) {
                    sInstance = new SimpleTaskExecutor();
                }
            }
        }
        return sInstance;
    }

    public void setDelegate(@Nullable TaskExecutor taskExecutor) {
        mDelegate = taskExecutor == null ? mDefaultTaskExecutor : taskExecutor;
    }

    @Override
    public void schedule(Runnable runnable) {
        mDelegate.schedule(runnable);
    }

    @Override
    public void scheduleSerial(Runnable r) {
        mDelegate.scheduleSerial(r);
    }

    @Override
    public void scheduleSerial(String group, Runnable r) {
        mDelegate.scheduleSerial(group, r);
    }

    @Override
    public void scheduleSerial(String group, Runnable r, boolean onlyRecent) {
        mDelegate.scheduleSerial(group, r, onlyRecent);
    }

    @Override
    public ScheduledFuture<Object> schedule(Runnable command, long delay, TimeUnit unit) {
        return mDelegate.schedule(command, delay, unit);
    }

    @Override
    public ScheduledFuture<Object> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        return mDelegate.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<Object> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        return mDelegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    @Override
    public void postToMainThread(Runnable runnable) {
        mDelegate.postToMainThread(runnable);
    }

    @Override
    public void postToMainThreadDelay(Runnable runnable, long delayTime) {
        mDelegate.postToMainThreadDelay(runnable, delayTime);
    }

    @Override
    public void removeRunnable(Runnable runnable) {
        mDelegate.removeRunnable(runnable);
    }

    @Override
    public boolean hasCallbacks(Runnable runnable) {
        return mDelegate.hasCallbacks(runnable);
    }

    @Override
    public boolean isMainThread() {
        return mDelegate.isMainThread();
    }
}
